package com.community.zhihuishequ.view.collect;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.community.zhihuishequ.R;
import com.community.zhihuishequ.db.HouseData;
import com.community.zhihuishequ.view.base.BaseFragment;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static android.widget.LinearLayout.VERTICAL;

/**
 * 住房信息
 */
public class CollectHouseFragment extends BaseFragment {

    @BindView(R.id.et_unit)
    EditText etUnit;
    @BindView(R.id.et_check_in_time)
    EditText etCheckInTime;
    @BindView(R.id.et_living_space)
    EditText etLivingSpace;
    @BindView(R.id.et_house_type)
    EditText etHouseType;
    @BindView(R.id.et_cohabitation_num)
    EditText etCohabitationNum;
    @BindView(R.id.rv_img_list)
    RecyclerView rvImgList;
    Unbinder unbinder;
    @BindView(R.id.rl_unit)
    RelativeLayout rlUnit;
    @BindView(R.id.rl_street)
    RelativeLayout rlStreet;
    @BindView(R.id.rl_room_num)
    RelativeLayout rlRoomNum;
    @BindView(R.id.rl_landlord)
    RelativeLayout rlLandlord;
    @BindView(R.id.rl_rent_date)
    RelativeLayout rlRentDate;
    @BindView(R.id.ll_img)
    LinearLayout llImg;
    private View rootView;

    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter adapter;
    private int themeId;
    public static final int REQUEST_SCAN_IDCARD = 2;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_collect_house, container, false);
        }
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        themeId = R.style.picture_default_style;
        initView();
    }

    private void initView() {
        String title = ((CollectFragmentActivity) getActivity()).tvTitle.getText().toString();
        if (title.equals(getResources().getString(R.string.collect_owner_tab1))) {
            rlUnit.setVisibility(View.VISIBLE);
        } else if (title.equals(getResources().getString(R.string.collect_lessee_tab1))) {
            rlStreet.setVisibility(View.VISIBLE);
            rlRoomNum.setVisibility(View.VISIBLE);
            rlLandlord.setVisibility(View.VISIBLE);
            rlRentDate.setVisibility(View.VISIBLE);
            llImg.setVisibility(View.VISIBLE);
            initImgList();
        }
        ((CollectFragmentActivity) getActivity()).btnSubmit.setText("提交");
    }

    private void initImgList() {
        FullyGridLayoutManager fullyGridLayoutManager = new FullyGridLayoutManager(getActivity(), 4, VERTICAL, false);
        fullyGridLayoutManager.setScrollEnabled(false);
        rvImgList.setLayoutManager(fullyGridLayoutManager);
        adapter = new GridImageAdapter(getActivity(), onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(9);
        rvImgList.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivity.this).themeStyle(themeId).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(CollectHouseFragment.this).themeStyle(themeId).openExternalPreview(position, selectList);
                            break;
                        default:
                            break;
                    }
                }
            }
        });
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            PictureSelector.create(CollectHouseFragment.this)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                    .maxSelectNum(9)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(4)// 每行显示个数
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                    .previewImage(true)// 是否可预览图片
//                    .previewVideo(cb_preview_video.isChecked())// 是否可预览视频
//                    .enablePreviewAudio(cb_preview_audio.isChecked()) // 是否可播放音频
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    //.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
//                    .enableCrop(cb_crop.isChecked())// 是否裁剪
//                    .compress(cb_compress.isChecked())// 是否压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    //.compressSavePath(getPath())//压缩图片保存地址
                    //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                    .withAspectRatio(aspect_ratio_x, aspect_ratio_y)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                    .hideBottomControls(cb_hide.isChecked() ? false : true)// 是否显示uCrop工具栏，默认不显示
//                    .isGif(cb_isGif.isChecked())// 是否显示gif图片
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
//                    .circleDimmedLayer(cb_crop_circular.isChecked())// 是否圆形裁剪
//                    .showCropFrame(cb_showCropFrame.isChecked())// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
//                    .showCropGrid(cb_showCropGrid.isChecked())// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
//                    .openClickSound(cb_voice.isChecked())// 是否开启点击声音
                    .selectionMedia(selectList)// 是否传入已选图片
                    //.isDragFrame(false)// 是否可拖动裁剪框(固定)
//                        .videoMaxSecond(15)
//                        .videoMinSecond(10)
                    //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                    //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                    //.rotateEnabled(true) // 裁剪是否可旋转图片
                    //.scaleEnabled(true)// 裁剪是否可放大缩小图片
                    //.videoQuality()// 视频录制质量 0 or 1
                    //.videoSecond()//显示多少秒以内的视频or音频也可适用
                    //.recordVideoSecond()//录制视频秒数 默认60s
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    protected void saveData(HouseData houseData) {
        houseData.unit = etUnit.getText().toString();
        houseData.checkInTime = etCheckInTime.getText().toString();
        houseData.livingSpace = etLivingSpace.getText().toString();
        houseData.houseType = etHouseType.getText().toString();
        houseData.cohabitationNum = etCohabitationNum.getText().toString();
        houseData.createTime = TimeUtils.getNowString();
        houseData.save();
        ToastUtils.showShort("保存成功");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
